package com.wellwan.cloud.user.controller;

import com.wellwan.cloud.user.entity.User;
import com.wellwan.cloud.user.repositoty.UserRepository;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collection;
import java.util.Objects;

/**
 * Copyright (C),微动天下
 * FileName: UserController
 * Author:   maokai
 * Date:     2020/2/21 10:14
 * Description:
 */
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/{id}")
    public User findById(@PathVariable Long id) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            UserDetails user = (UserDetails) principal;
            Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
            for (GrantedAuthority auth : authorities) {
                log.info("当前用户是{},角色是{}", user.getUsername(), auth.getAuthority());
            }
        }else{
            log.info("其他功能-----");
        }
        User user = this.userRepository.findOne(id);
        return user;
    }
    @PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String upload(MultipartFile file) {
        if (Objects.isNull(file)) {
            throw new RuntimeException("文件不存在");
        }
        return file.getName();
    }

}
